<template>
    <div>
        <slot></slot>
    </div>
    <div :class='$style.pagination'>
        <template v-if='props.showLoading'>
            <a-spin v-if='loading' />
        </template>
        <a-pagination :showTotal='total => showTotal(total)' background show-size-changer v-model:current='pageNo'  v-model:pageSize='pageSize' :disabled='loading' :pageSizeOptions='pageSizes' :total='total' @change='pageNoChange' @showSizeChange='pageSizeChange' />
    </div>
</template>

<script lang='ts' setup>
import { useI18nStore } from "@/store/i18n";
import { nextTick, reactive, ref } from "vue";
    
    const props = withDefaults(defineProps<{
        api : (params:any) => any,
        showLoading : boolean
    }>(), {
        showLoading : true
    })

    const emit = defineEmits<{
        (e : 'finish', rows:any[]) : void
    }>()

    const i18n = useI18nStore()

    const loading = ref(false)
    const pageSizes = reactive(['10', '20', '50', '100'])
    const pageNo = ref(1)
    const pageSize = ref(Number(pageSizes[1]))
    const total = ref(0)

    const showTotal = (t) => {
        return i18n.t('pageTotal') + ' ' + t + ' ' + i18n.t('pageRowData')
    }

    async function load() {
		if(loading.value) return
		loading.value = true
		const res = await props.api({pageNo : Number(pageNo.value), pageSize : Number(pageSize.value)})
		loading.value = false

		let list = []

		if(res.data) {
			total.value = res.data.total
			list = res.data.rows || []
		}else {
			total.value = 0
		}


		emit('finish', list)
	}

    function reload() {
        pageNo.value = 1
        nextTick(() => {
            load()
        })
    }
    
    function pageNoChange() {
        load()
    }

    function pageSizeChange() {
        load()
    }

    load()

    defineExpose({
        loading,
        load,
        reload
    })

</script>

<style scoped module lang='scss'>
    .pagination{
        display: flex;
        align-items: center;
        gap: 20px;
        justify-content : right;
        margin-top: 20px;
    }
</style>